package com.smbms.interceptor;

import com.smbms.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入了拦截器");
        //如果是OPTIONS请求方式，放行
       if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            //直接放行
            return true;
        }
        String token = request.getHeader("Authorization");
        if(token==null){
           throw new Exception("没有token");
        }
        Claims claims = jwtUtil.parseJWT(token);
        if(claims==null){
            throw new Exception("权限不足");
        }
        Object role = claims.get("roles");
        if("1".equals(role)){
            request.setAttribute("role","admin");
        }else{
            request.setAttribute("role","user");
        }

        return true;
    }
}
